<?php
namespace Components\Account\User\Message;

class Service {
	private $models = [];
	public function getModelsById($id = null) {
		if(is_null($id)) {
			return $this -> models;
		}

		if(!is_numeric($id) || $id <= 0) {
			return false;
		}

		if(isset($this -> models[$id]) && !empty($this -> models[$id]) && is_object($this -> models[$id])) {
			return $this -> models[$id];
		}

		$model = $this -> findFirstById($id);
		if($model['code'] != 0) {
			return false;
		}

		return $this -> models[$id] = $model['user_message'];
	}

	public function findFirstById($id) {
		if($id <= 0) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return $this -> findFirst(['message_id = ' . $id]);
	}

	public function findFirst($parameters = []) {
		$model = Model::findFirst($parameters);
		if(!$model) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return ['code' => 0, 'user_message'=>$model];
	}

	public function pager($parameters = [], $limit = 10, $page = 1) {
		$builder = (new \Phalcon\Mvc\Model\Query\Builder($parameters)) -> from([
			'um' => __NAMESPACE__ . '\\Model',
			'u' => \Components\Account\User\Model::class
		])
		-> columns(
			'um.message_id, um.user_id, um.title, um.content, um.create_time, um.reply_time, um.replay_content, um.status, '.
			'u.account'
		)
		-> andWhere('um.user_id = u.user_id');
		return ['code' => 0, 'pager'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
			'builder' => $builder,
			'limit' => $limit,
			'page' => $page
		])) -> getPaginate()];
	}

	public function create($data) {
		$model = new Model($data);
		if(!$model -> create()) {
			$messages = $model -> getMessages();
			return ['code' => -1, 'message' => $messages[0] -> getMessage()];
		}

		return ['code' => 0, 'message'=>$model];
	}

	public function update($id, $data) {
		if(!$this -> getModelsById($id)) {
			return ['code' => -1, 'message'=>'数据不存在或已删除'];
		}

		if(!$this -> models[$id] -> update($data)) {
			$messages = $this -> models[$id] -> getMessages();
			return ['code' => -1, 'message' => $messages[0] -> getMessage()];
		}

		return ['code' => 0, 'user_message'=>$this -> models[$id]];
	}
	
}
